package org.neowei.image.commond.Handle;

import java.io.IOException;

import org.neowei.common.exception.CommondException;
import org.neowei.image.api.ImageOption;
import org.neowei.image.commond.CmdOption;
import org.neowei.image.commond.CommondContorl;

public abstract class AbstractHandle {
	protected String despathWithFilename;
	protected String srcpathWithFilename;
	protected ImageOption imageOption;

	final protected void crop(CmdOption option) throws InterruptedException {
		CommondContorl cmd = new CommondContorl();
		try {
			String errormessage = cmd.getErrorResult(cmd.startCommond(option.toString()));
			if (!(null == errormessage || errormessage.length() == 0)) {
				throw new CommondException(errormessage);
			}
		} catch (IOException e) {
			throw new CommondException("gm cmd crop image i/o error", e);
		}
	}

	final protected String getStrHeightWidth(int width, int height) {
		return new StringBuilder().append(width > 0 ? width : "").append("x").append(height > 0 ? height : "").toString();
	}

	final protected CmdOption getCmdOption(String cmd) {
		CmdOption cmdOption = new CmdOption();
		cmdOption.setCmd(cmd);
		cmdOption.setSrcpathWithFilename(this.srcpathWithFilename);
		cmdOption.setDesPathWithFilename(this.despathWithFilename);
		return cmdOption;
	}

	public abstract void doHandle(ImageOption imageOption) throws Exception;

	public String getDespathWithFilename() {
		return this.despathWithFilename;
	}

	public AbstractHandle setImageOption(ImageOption imageOption) {
		this.imageOption = imageOption;
		this.srcpathWithFilename = imageOption.getSrcpathWithFilename();
		this.despathWithFilename = imageOption.getDespathWithFilename();
		return this;
	}
}
